package com.gofaraway.start.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import javax.validation.constraints.NotNull;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author ChenPeng
 * @Date 2024/1/15 18:32
 */
@Slf4j
@Configuration
public class AsyncConfigIntegration implements AsyncConfigurer {


    public static final int CORE_POOL_SIZE = 5;

    public static final int MAX_POOL_SIZE = 10;
    public static final int KEEP_ALIVE_SECONDS = 15;
    public static final int QUEUE_CAPACITY = 100;



    @Override
    @Bean("asyncExecutor")
    public Executor getAsyncExecutor() {
        return getExecutor(CORE_POOL_SIZE, MAX_POOL_SIZE);
    }


    @NotNull
    private Executor getExecutor(int corePoolSize, int maxPoolSize) {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(QUEUE_CAPACITY);
        executor.setKeepAliveSeconds(KEEP_ALIVE_SECONDS);
        executor.setRejectedExecutionHandler((new ThreadPoolExecutor.CallerRunsPolicy()));
        executor.initialize();
        return executor;
    }

    /**
     * 配置异常处理机制
     *
     * @return
     */
    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return (ex, method, params) -> log.error("异步线程执行失败。方法：[{}],异常信息[{}] : ", method, ex.getMessage(), ex);
    }
}